package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.memberDto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.task.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.memberVo.DeviceDetailVo;
import com.zzyl.nursing.vo.memberVo.DeviceReportDataVo;
import com.zzyl.nursing.vo.memberVo.ProductsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备Service业务层处理
 *
 * @author yhy
 * @date 2025-09-26
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient iotDAClient;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        // 从IOT 获取产品列表
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = iotDAClient.listProducts(listProductsRequest);
        if(ObjectUtil.isEmpty( response)){
            throw new BaseException("获取产品列表失败");
        }
        // 将产品列表 保存redis
        redisTemplate.opsForValue().set(CacheConstants.PROJECT_ALL_KEY, JSONUtil.toJsonStr(response.getProducts()));

    }

    /**
     * 从redis中 获取产品列表
     * @return
     */
    @Override
    public List<ProductsVo> allProduct() {

        // 从redis 获取产品列表
        String products = redisTemplate.opsForValue().get(CacheConstants.PROJECT_ALL_KEY);
        // 判断redis中有没有产民
        if(StringUtils.isEmpty(products)){
            // 没有则返回一个空集合
            return Collections.emptyList();
        }
        // 返回产品列表
        return JSONUtil.toList(products,ProductsVo.class);
    }

    /**
     * 注册设备
     * @param deviceDto 设备信息
     */
    @Override
    public void register(DeviceDto deviceDto) {

        // 判断设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(count > 0){
            // 抛出异常 设备名称重复
            throw new BaseException("设备名称重复");
        }
        // 判断设备标识码是否重复
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if(count > 0){
            // 抛出异常 设备标识码重复
            throw new BaseException("设备标识码重复");
        }
        // 判断同一位置不可以保存相同的产品
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getPhysicalLocationType() != null ,Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey()));
        if(count > 0){
            // 抛出异常 同一位置不可以保存相同的产品
            throw new BaseException("同一位置或老人不可以保存相同的产品");
        }


        /* 添加设备 */

        // 添加到Iot
        AddDeviceRequest request = new  AddDeviceRequest();
        AddDevice body = new AddDevice();
        // 设备标识码
        body.setNodeId(deviceDto.getNodeId());
        // 设备名称
        body.setDeviceName(deviceDto.getDeviceName());
        // 设备所属产品
        body.setProductId(deviceDto.getProductKey());
        // 设备密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);

        // 封装设备信息   并调用iot  添加设备
        request.setBody(body);
        AddDeviceResponse response;
        try {
            response = iotDAClient.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("添加设备失败!");
        }

        /* 添加到数据库 */
        Device device = BeanUtil.toBean(deviceDto,Device.class);
        // 获取设备ID
        String deviceId = response.getDeviceId();
        device.setIotId(deviceId);
        device.setSecret(secret);

        // 判断位置类型， 如果为0（随身设备）就把物理位置类型改为 -1
        if(device.getLocationType() == 0){
            device.setPhysicalLocationType(-1);
        }

        device.setCreateTime(DateUtils.getNowDate());
        save(device);

    }

    /**
     * 获取设备详情
     * @param iotId 设备ID
     * @return 设备详情
     */
    @Override
    public DeviceDetailVo getDeviceById(String iotId) {

        /* 获取设备信息 */
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));


        /* 调用iot  获取设备 状态、时间 */
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(device.getIotId());
        // 获取华为云响应体
        ShowDeviceResponse response;
        try {
            response = iotDAClient.showDevice(request);
        } catch (Exception e){
            throw new BaseException("获取设备信息失败!");
        }

        /* 封装设备信息 */
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        // 获取响应体 中设备激活时间、状态
        String activeTimeStr = response.getActiveTime();

        if(!StringUtils.isEmpty(activeTimeStr)){
            LocalDateTime dateTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 同步激活时间为 东8区时间 并设置时间
            deviceDetailVo.setActiveTime(DateTimeZoneConverter.utcToShanghai(dateTime));
        }

        // 获取设备状态
        String status = response.getStatus();
        deviceDetailVo.setDeviceStatus( status);



        /* 返回设备信息 */
        return deviceDetailVo;
    }

    /**
     * 查询设备服务属性
     * @param iotId 设备ID
     * @return List<DeviceReportDataVo> 设备服务属性
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        // 获取 iot 响应体
        ShowDeviceShadowResponse response;
        try {
            response = iotDAClient.showDeviceShadow(request);
        } catch (Exception e) {
            throw new BaseException("获取设备数据失败!");
        }

        // 从响应体中 获取设备数据
        DeviceShadowData shadow = response.getShadow().get(0);

        if(ObjectUtil.isEmpty( shadow)){
            // 如果设备数据为空 返回一个空集合
            return Collections.emptyList();
        }

        // 获取 设备中的数据
        DeviceShadowProperties reported = shadow.getReported();

        // 获取上传数据时间
        String eventTime = reported.getEventTime();
        LocalDateTime dateTime = LocalDateTimeUtil.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        // 转换为东8区时间
        LocalDateTime eventTimeShanghai = DateTimeZoneConverter.utcToShanghai(dateTime);

        // 获取 reported
        Object object = reported.getProperties();
        JSONObject deviceData = JSONUtil.parseObj(object);

        // 准备一个集合 用于返回设备数据
        List<Map<String, Object>> list = new ArrayList<>();

        deviceData.forEach((key,value)->{
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            // 时间是从  response.getShadow().get(0); 拿到的，拿到的是数组（设备数据）中的第一个元素
            map.put("eventTime", eventTimeShanghai);
            list.add(map);
        });

        return list;

    }

    /**
     * 根据设备DTO中的位置信息查询单个设备记录
     * 通过绑定位置、位置类型、物理位置类型和产品ID等条件进行精确匹配查询
     *
     * @param deviceDto 包含查询条件的设备数据传输对象，用于提供位置相关查询参数
     * @return 返回匹配条件的单个设备对象，如果未找到则返回null
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDeviceById(DeviceDto deviceDto) {

        // 更新数据库设备信息
        Device device = BeanUtil.toBean(deviceDto,Device.class);
        try {
            updateById(device);
        } catch (Exception e) {
            throw new BaseException("该老人或楼层已经绑定相同的设备了，请误重新绑定！");
        }
        // 更新 华为云 设备信息
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());

        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(device.getDeviceName());
        body.setDescription(device.getDeviceDescription());
        request.setBody(body);
        try {
            iotDAClient.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("更新华为云设备失败");
        }

    }


    /**
     * 根据设备ID删除设备
     * @param iotId 设备ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDeviceByIotId(String iotId) {
        // 删除数据库设备信息
        deviceMapper.deleteDeviceByIotId(iotId);
        // 删除华为云设备信息

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        iotDAClient.deleteDevice(request);
    }

    /**
     * 查询产品信息
     *
     * @param productKey 产品Key
     * @return AjaxResult
     */
    @Override
    public AjaxResult queryProduct(String productKey) {

        // 判断产品id是否为空
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("产品ID不能为空");
        }

        // 获取华为云 响应体
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response;
        try {
            response = iotDAClient.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("获取华为云产品信息失败！");
        }

        // 获取产品信息
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(ObjectUtil.isEmpty(serviceCapabilities)){
            // 返回空集合
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
